<?php

/**
 * Normalize path: remove "../", "./" and duplicated slashes
 *
 * @param string $path
 * @param string $separator
 * @return string normilized path
 */
function fn_normalize_path($path, $separator = '/')
{

	$result = array();
	$path = preg_replace("/[\\\\\/]+/S", $separator, $path);
	$path_array = explode($separator, $path);
	if (!$path_array[0])  {
		$result[] = '';
	}

	foreach ($path_array as $key => $dir) {
		if ($dir == '..') {
			if (end($result) == '..') {
			   $result[] = '..';
			} elseif (!array_pop($result)) {
			   $result[] = '..';
			}
		} elseif ($dir != '' && $dir != '.') {
			$result[] = $dir;
		}
	}

	if (!end($path_array)) {
		$result[] = '';
	}

	return fn_is_empty($result) ? '' : implode($separator, $result);
}
/**
 * Create directory wrapper. Allows to create included directories
 *
 * @param string $dir
 * @param int $perms permission for new directory
 */
function fn_mkdir($dir, $perms = DEFAULT_DIR_PERMISSIONS)
{
	$result = false;

	// Truncate the full path to related to avoid problems with
	// some buggy hostings
	if (strpos($dir, DIR_ROOT) === 0) {
		$dir = './' . substr($dir, strlen(DIR_ROOT) + 1);
		$old_dir = getcwd();
		chdir(DIR_ROOT);
	}

	if (!empty($dir)) {
		$result = true;
		if (@!is_dir($dir)) {
			$dir = fn_normalize_path($dir, '/');
			$path = '';
			$dir_arr = array();
			if (strstr($dir, '/')) {
				$dir_arr = explode('/', $dir);
			} else {
				$dir_arr[] = $dir;
			}

			foreach ($dir_arr as $k => $v) {
				$path .= (empty($k) ? '' : '/') . $v;
				if (!@is_dir($path)) {
					umask(0);
					mkdir($path, $perms);
				}
			}
		}
	}

	if (!empty($old_dir)) {
		chdir($old_dir);
	}
	return $result;
}

/**
 * Get file extension
 *
 * @param string $filename
 */
function fn_get_file_ext($filename)
{
	$i = strrpos($filename, '.');
	if ($i === false) {
		return '';
	}

	return substr($filename, $i + 1);
}


?>